package com.neusoft.controller;

import com.neusoft.po.CommonResult;
import com.neusoft.po.Credit;
import com.neusoft.service.CreditService;
import com.neusoft.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/CreditController")
@RefreshScope
public class CreditController {

    @Autowired
    private CreditService creditService;

    // 使用积分
    @PostMapping("/use/{userId}/{pointsToUse}")
    public CommonResult<Integer> usePoints(@PathVariable("userId") String userId,
                                  @PathVariable("pointsToUse") Integer pointsToUse) {

        Credit credit = new Credit();
        credit.setUserId(userId);
        credit.setType("CONSUME");
        credit.setNum(-1*pointsToUse);
        credit.setChangeTime(CommonUtil.getNow());
        credit.setStatus(-1);

        return new CommonResult<>(200, "success", creditService.updateCredit(credit));
    }

    // 增加积分
    @PostMapping("/add/{userId}/{pointsToAdd}")
    public CommonResult<Integer> addPoints(@PathVariable("userId") String userId,
                                  @PathVariable("pointsToAdd") Integer pointsToAdd) {
        Credit credit = new Credit();
        credit.setUserId(userId);
        credit.setType("ORDER");
        credit.setNum(pointsToAdd);
        credit.setChangeTime(CommonUtil.getNow());
        credit.setExpire_time(CommonUtil.getNowToExpire());
        credit.setStatus(1);

        return new CommonResult<>(200, "success", creditService.updateCredit(credit));
    }

    // 获取用户的可用积分
    @GetMapping("/available/{userId}")
    public CommonResult<List<Credit>> getAvailablePoints(@PathVariable("userId") String userId) {
        return new CommonResult<>(200, "success", creditService.getCreditByUserId(userId));
    }

    // 获取用户的过期积分
    @GetMapping("/expired/{userId}")
    public CommonResult<List<Credit>> getExpiredPoints(@PathVariable("userId") String userId) {
        return new CommonResult<>(200, "success", creditService.getExpiredPoints(userId));
    }

    // 获取用户的总可用积分
    @GetMapping("/total/{userId}")
    public CommonResult<Integer> getTotalAvailablePoints(@PathVariable("userId") String userId) {
        return new CommonResult<>(200, "success", creditService.getTotalCreditByUserId(userId));
    }

    @PostMapping("/initCredit/{userId}")
    public CommonResult<Integer> initCredit(@PathVariable("userId")String userId){
        Credit credit = new Credit();
        credit.setUserId(userId);
        return new CommonResult<>(200, "success", creditService.initCredit(credit));
    }

    @PostMapping("/refresh")
    public CommonResult<Integer> refreshExpiredCredit(){
        return new CommonResult<>(200, "success", creditService.updateExpiredPoints());
    }
}
